<template>
  <div class="ShowChart">
    <el-row style="padding: 10px; font-size: 14px">
      <el-col :span="5"
        ><div class="quotaDim" style="height: 100%">
          <div
            class="quotatree"
            style="border: 1px solid #dfe4ed; height: 400px; margin-bottom: 5px"
          >
            <QuotaTree
              @dragNode="handleDragNode"
              class="quoTree"
              :showcheckbox="false"
            />
          </div>
          <div
            style="
              height: 420px;
              text-align: center;
              overflow: auto;
              border: 1px solid #d8dce5;
            "
          >
            <div
              class="commomDim"
              style="
                height: 32px;
                line-height: 32px;
                text-align: center;
                border: 1px solid #d8dce5;
              "
            >
              共有维度
            </div>
            <div class="common">
              <el-tree
                draggable
                :allow-drop="nodeDrop"
                @node-drag-start="colDragEnd"
                node-key="id"
                ref="dimTree"
                :data="commonDimensionList"
                :props="dimTreeProps"
              ></el-tree>
            </div>
          </div></div
      ></el-col>
      <el-col style="padding: 0 5px" :span="4"
        ><div class="chartsType">
          <div
            class="type"
            style="
              padding: 5px;
              border: 1px solid #dfe4ed;
              height: 400px;
              text-align: center;
              margin-bottom: 5px;
            "
          >
            <div style="margin: 5px 5px 15px 5px">图表类型</div>

            <div>
              <el-tooltip
                v-for="(item, index) in chartsType"
                :key="index"
                :content="item.tip"
                placement="bottom"
                effect="light"
              >
                <!-- <el-tag
                  @click="changeChart(index)"
                  style="margin: 5px;display:block"
                  type="info"
                  effect="plain"
                  > {{item.value}}
                </el-tag> -->
                <el-image
                  class="chartType"
                  style="width: 30px; height: 30px; margin: 8px"
                  :src="item.url"
                  @click="changeChart(item.backgroundUrl, index)"
                ></el-image>
              </el-tooltip>
            </div>
          </div>
          <div
            class="config"
            style="
              padding: 10px;
              border: 1px solid #dfe4ed;
              height: 420px;
              text-align: center;
            "
          >
            <div style="margin: 5px 10px 15px 10px">图表配置</div>

            <div>
              
              <el-checkbox-group v-model="checkList">
                <el-checkbox
                  border
                  style="margin: 6px 0; width: 100%; display: block"
                  v-for="(item, index) in config"
                  :key="index"
                  :label="index"
                  >{{ item }}</el-checkbox
                >
              </el-checkbox-group>
              <el-input @change="changeTitle" v-model="chartTitle" style="margin-bottom:6px " placeholder="请输入图表标题"></el-input>
              <el-input
                type="number"
                v-model="showLimit"
                @change="defineDimensionNum"
                suffix-icon="el-icon-tickets"
                placeholder="请输入展示维度条数"
              ></el-input>
            </div>
          </div></div
      ></el-col>
      <el-col style="padding: 0 20px 10px 10px" :span="15"
        ><div class="charts">
          <div
            class="row"
            @drop="dropRow"
            @dragover.prevent
            style="
              border: 1px solid #dfe4ed;
              height: 40px;
              padding: 0 10px;
              line-height: 40px;
            "
          >
            横轴
            <el-dropdown
              v-for="(item, index) in rowList"
              :key="item.id"
              trigger="click"
            >
              <el-tag class="el-dropdown-link" style="margin: 0 5px"
                >{{ item.name ? item.name : item.dimensionName }}
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-tag>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleClose(item, index)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div
            @drop="dropCol"
            @dragover.prevent
            class="col"
            style="
              padding: 0 10px;
              border: 1px solid #dfe4ed;
              height: 40px;
              line-height: 40px;
              margin: 10px 0;
            "
          >
            纵轴
            <el-dropdown
              v-for="(item, index) in colList"
              :key="item.id"
              trigger="click"
            >
              <el-tag class="el-dropdown-link" style="margin: 0 5px"
                >{{ item.dimensionName ? item.dimensionName : item.name }}
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-tag>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleCloseCol(item, index)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div
            class="chart"
            v-loading="loading"
            style="padding: 10px; border: 1px solid #dfe4ed; height: 600px"
            :style="{ background: `url(${backgroundUrl}) center no-repeat` }"
          >
            {{chartTitle||"图表"}}
            <div v-if="showChart === 0" class="table">
              <PivotChart :data="data" :slice="slice" />
            </div>
            <div
              style="margin-top: 80px"
              v-if="showChart === 1"
              class="barChart"
            >
              <BarChart
                :xAxis="xAxis"
                :yAxis="yAxis"
                :grid="grid"
                :legend="legend"
                :toolbox="toolbox"
                :title="title"
                :data="chartData"
                :quotaIds="quotaIds"
              />
            </div>
            <div
              style="margin-top: 100px"
              v-if="showChart === 2"
              class="lineChart"
            >
              <LineChart
                :xAxis="xAxis"
                :yAxis="yAxis"
                :grid="grid"
                :legend="legend"
                :toolbox="toolbox"
                :title="title"
                :data="chartData"
                :quotaIds="quotaIds"
              />
            </div>

            <div
              style="margin-top: 100px"
              v-if="showChart === 3"
              class="pieChart"
            >
              <PieChart
                :showLeg="showLeg"
                :grid="grid"
                :legend="legend"
                :toolbox="toolbox"
                :title="title"
                :data="chartData"
              />
            </div>
            <div
              style="margin-top: 80px"
              v-if="showChart === 4"
              class="scatterChart"
            >
              <ScatterChart
                :xAxis="xAxis"
                :yAxis="yAxis"
                :grid="grid"
                :legend="legend"
                :toolbox="toolbox"
                :title="title"
                :data="chartData"
                :quotaIds="quotaIds"
              />
            </div>
            <div
              style="margin-top: 80px"
              v-if="showChart === 5"
              class="radarChart"
            >
              <RadarChart
                :legend="legend"
                :toolbox="toolbox"
                :title="title"
                :data="chartData"
                :quotaIds="quotaIds"
              />
            </div>
          </div>
          <div style="margin: 10px 0">
            <el-select
              style="margin-right: 10px"
              v-model="typeId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in computedType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div style="margin: 10px 0 0">
            <el-tooltip
              class="item"
              effect="dark"
              content="为保证流畅性,非必要情况下,请不要勾选"
              placement="top-start"
            >
              <el-checkbox @change="showAllData" v-model="allData"
                >查看所有数据</el-checkbox
              >
            </el-tooltip>
          </div>

          <el-button
            style="margin-top: 10px"
            type="primary"
            @click="createChart"
            >生成图表</el-button
          >
        </div></el-col
      >
    </el-row>
  </div>
</template>
<script>
import BarChart from "@/components/echarts/barChart.vue";
import RadarChart from "@/components/echarts/radarChart.vue";
import LineChart from "@/components/echarts/lineChart.vue";
import ScatterChart from "@/components/echarts/scatterChart.vue";
import PieChart from "@/components/echarts/pieChart.vue";
import QuotaTree from "@/views/quota/modeling/QuotaTree.vue";
import PivotChart from "@/views/quota/PivotChart/index.vue";
import {
  getBeMixedTree,
  getBarChartsJson,
  getPieChartsJson,
  getReportJson,
  getScatterChartsJson,
  queryComputeType,
} from "@/api/quota/define/define.js";
export default {
  name: "index",
  components: {
    ScatterChart,
    QuotaTree,
    BarChart,
    LineChart,
    RadarChart,
    PieChart,
    PivotChart,
  },
  data() {
    return {
      //图标标题
      chartTitle:"",
      //图表配置项
      checkList: [],
      //数据透视表行列配置项
      slice: {
        columns: [],
        rows: [],
        measures: [],
      },
      //背景图片
      bgUrl: "",
      backgroundUrl: "",
      //自定义维度条数
      showLimit: "",
      //图形条数
      limit: 6,
      //x轴配置
      xAxis: [],
      //y轴配置
      yAxis: [],
      //指标列
      quotaList: [],
      //维度列
      dimensionList: [],
      //计算类型
      computedType: [],
      //指标值类型
      typeId: "0",
      //显示图例
      showLeg: false,
      //指标Id
      quotaIds: [],
      //数据透视表数据
      data: [],
      //查看所有数据
      allData: false,
      //网格
      grid: {
        top: 60,
        width: 850,
        height: 250,
        left: "2%",
        right: "2%",
        bottom: "3%",
        containLabel: true,
      },
      //标题
      title: {},
      //图例
      legend: [],
      //工具栏
      toolbox: {},
      //选中图标类型
      currentType: 0,
      chartData: [],
      loading: false,
      //图表配置项
      showChart: null,
      //图标类型
      chartsType: [
        {
          value: "表格",
          tip: "数据透视图",
          url: "/chartsImg/table.png",
          backgroundUrl: "/chartsImg/table_group.png",
        },
        {
          value: "柱状图",
          tip: "建议至少2个指标,至少1个维度",
          url: "/chartsImg/bar.png",
          backgroundUrl: "/chartsImg/bar_group.png",
        },
        {
          value: "折线图",
          tip: "建议至少1个指标,至少1个维度",
          url: "/chartsImg/line.png",
          backgroundUrl: "/chartsImg/line_group.png",
        },

        {
          value: "饼图",
          tip: "建议1个指标,1个维度",
          url: "/chartsImg/pie.png",
          backgroundUrl: "/chartsImg/pie_group.png",
        },
        {
          value: "关系图",
          tip: "建议至多三个指标,六个维度",
          url: "/chartsImg/scatter.png",
          backgroundUrl: "/chartsImg/scatter_group.png",
        },
        {
          value: "雷达图",
          tip: "建议至少1个指标,至少1个维度",
          url: "/chartsImg/radar.png",
          backgroundUrl: "/chartsImg/radar_group.png",
        },
        // {
        //   value: "气泡图",
        //   tip: "建议至多三个指标,六个维度",
        //   url: "/chartsImg/bubble.png",
        // },
        // {
        //   value: "横向柱状图",
        //   tip: "建议至多三个指标,六个维度",
        //   url: "/chartsImg/bar_hor.png",
        // },
        // {
        //   value: "瀑布图",
        //   tip: "建议至多三个指标,六个维度",
        //   url: "/chartsImg/waterFall.png",
        // },
        // {
        //   value: "范围面积图",
        //   tip: "建议至少2个指标,至少1个维度",
        //   url: "/chartsImg/rangeArea.png",
        // },
      ],
      //配置信息
      config: ["显示图例", "显示工具栏"],
      //配置选项下标
      configIndex: undefined,
      dimTreeProps: {
        children: "children",
        label: "dimensionName",
      },
      themeId: undefined,
      currentTabComponent: "define",
      commonDimensionList: [],
      rowList: [],
      colList: [],
      selectNode: undefined,
      selectNode: undefined,
    };
  },
  computed: {},
  watch: {
    quotaList: {
      handler(newVal, oldVal) {
        if (this.quotaList.length > 0) {
          let quotaIds = [];
          this.quotaList.forEach((item) => {
            quotaIds.push(item.id);
          });
          getBeMixedTree(quotaIds).then((res) => {
            this.commonDimensionList = this.handleTree(
              res.data,
              "id",
              "upperId"
            );
          });
        } else {
          this.commonDimensionList = [];
        }
      },
      deep: true,
    },
  },
  created() {
    //获取计算类型
    queryComputeType().then((res) => {
      this.computedType = res.data;
    });
  },
  mounted() {
    this.changeChart("/chartsImg/table_group.png", 0);
  },
  methods: {
    //设置标题
    changeTitle(){
      this.title = {
        text:this.chartTitle
      }
    },
    //阻止节点默认拖拽
    nodeDrop() {
      return false;
    },
    //自定义维度条数
    defineDimensionNum() {
      this.limit = Number(this.showLimit);
    },
    //查看所有数据
    showAllData() {
      if (this.allData) {
        this.limit = 0;
      } else {
        this.limit = 6;
      }
    },

    //图表配置项
    setConfig(index) {
      this.configIndex = index;
       if (index === 0) {
        let arr = [];
        this.quotaList.forEach((item) => {
          arr.push(item.name);
        });
        this.legend = arr;
        this.showLeg = true;
      } else if (index === 1) {
        this.toolbox = {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            dataView: { readOnly: false },
            magicType: { type: ["line", "bar"] },
            restore: {},
            saveAsImage: {},
          },
        };
      }
    },
    //点击图标类型按钮
    changeChart(url, index) {
      this.currentType = index;
      this.bgUrl = url;
      this.createChart();
    },
    //生成图表
    createChart() {
      this.legend = [];
      this.showLeg = false;
      this.toolbox = {};
      this.showChart = null;
      // this.showChart = 0
      let param = this.assemblyParams();
      if (this.rowList.length === 0 || this.colList.length === 0) {
        this.backgroundUrl = this.bgUrl;
        // this.$message("请先选择指标和公共维度");
        return;
      }
      this.backgroundUrl = "";
      this.loading = true;
      this.checkList.forEach((idx) => {
        this.setConfig(idx);
      });
      if (this.currentType === 1 || this.currentType === 2) {
        getBarChartsJson(param).then((res) => {
          this.loading = false;
          this.chartData = JSON.parse(res.data);
          if (this.rowList[0].isQuota) {
            this.xAxis = [
              {
                type: "value",
                axisTick: {
                  show: false,
                },
              },
            ];
            this.yAxis = [
              {
                type: "category",
                data: this.chartData["xAxis"],
                axisTick: {
                  alignWithLabel: true,
                },
              },
            ];
          } else {
            this.yAxis = [
              {
                type: "value",
                axisTick: {
                  show: false,
                },
              },
            ];
            this.xAxis = [
              {
                type: "category",
                axisLabel: {
                  interval: 0,
                  rotate: 10,
                },
                data: this.chartData["xAxis"],
                axisTick: {
                  alignWithLabel: true,
                },
              },
            ];
          }

          this.showChart = this.currentType;
        });
      } else if (this.currentType === 0) {
        //生成数据透视图

        getReportJson(param).then((res) => {
          this.loading = false;
          this.data = JSON.parse(res.data);
          this.slice = {
            columns: [],
            rows: [],
            measures: [],
          };
          if (this.rowList[0].isQuota) {
            this.quotaList.forEach((item) => {
              this.slice.columns.push({ uniqueName: item.name });
              this.slice.measures.push({
                uniqueName: item.name,
                aggregation: "count",
                level: "数量",
              });
            });
            let keys = Object.keys(this.data[0]);
            keys.forEach((key) => {
              let idx = key.indexOf("指标");
              if (idx === -1) {
                this.slice.rows.push({ uniqueName: key });
              }
            });
          } else {
            this.quotaList.forEach((item) => {
              this.slice.rows.push({ uniqueName: item.name });
              this.slice.measures.push({
                uniqueName: item.name,
                aggregation: "count",
                level: "数量",
              });
            });
            let keys = Object.keys(this.data[0]);
            keys.forEach((key) => {
              let idx = key.indexOf("指标");
              if (idx === -1) {
                this.slice.columns.push({ uniqueName: key });
              }
            });
          }
          this.showChart = this.currentType;
        });
      } else if (this.currentType === 3) {
        if (this.rowList.length > 1) {
          this.$message({
            message: "只能选择一个指标",
            type: "warning",
          });
          return;
        }

        getPieChartsJson(param).then((res) => {
          this.loading = false;
          this.chartData = JSON.parse(res.data);
          this.showChart = this.currentType;
        });
      } else if (this.currentType === 4) {
        getScatterChartsJson(param).then((res) => {
          this.loading = false;
          this.chartData = JSON.parse(res.data);

          if (this.rowList[0].isQuota) {
            this.quotaIds.forEach((id) => {
              this.chartData[id].forEach((item) => {
                item.reverse();
              });
            });
            this.xAxis = [
              {
                type: "value",
                axisTick: {
                  show: false,
                },
              },
            ];
            this.yAxis = [
              {
                type: "category",
                data: this.chartData["xAxis"],
                axisTick: {
                  alignWithLabel: true,
                },
              },
            ];
          } else {
            this.yAxis = [
              {
                type: "value",
                axisTick: {
                  show: false,
                },
              },
            ];
            this.xAxis = [
              {
                type: "category",
                data: this.chartData["xAxis"],
                axisLabel: {
                  interval: 0,
                  rotate: 10,
                },
                axisTick: {
                  alignWithLabel: true,
                },
              },
            ];
          }
          this.showChart = this.currentType;
        });
      } else if (this.currentType === 5) {
        //生成雷达图

        getBarChartsJson(param).then((res) => {
          this.loading = false;
          this.chartData = JSON.parse(res.data);
          this.showChart = this.currentType;
        });
      }
    },
    getLeafDimId(node, arr) {
      if (!node.children) {
        arr.push(node.id);
      } else {
        node.children.forEach((item) => {
          this.getLeafDimId(item, arr);
        });
      }
    },
    assemblyParams() {
      //组装查询条件
      let param = {
        limit: this.limit,
        type: this.typeId,
        quota: {},
        dimension: [],
      };
      //组装指标
      this.quotaIds = [];
      this.quotaList.forEach((item) => {
        this.quotaIds.push(item.id);
        param.quota[item.id + ""] = item.name;
      });
      //组装维度id
      this.dimensionList.forEach((item) => {
        //递归获取叶子维度
        this.getLeafDimId(item, param.dimension);
        // param.dimension.push(item.id);
      });
      return param;
    },
    //双击删除纵轴节点
    handleCloseCol(item, index) {
      this.colList.splice(index, 1);
      if (item.isQuota) {
        let idx = this.quotaList.findIndex((ele) => {
          return ele.id === item.id;
        });
        this.quotaList.splice(idx, 1);
      } else {
        let idx = this.dimensionList.findIndex((ele) => {
          return ele.id === item.id;
        });
        this.dimensionList.splice(idx, 1);
      }
    },
    //拖拽公共维度
    colDragEnd(node) {
      this.selectNode = node.data;
    },
    //双击删除横轴节点
    handleClose(item, index) {
      this.rowList.splice(index, 1);
      if (item.isQuota) {
        let idx = this.quotaList.findIndex((ele) => {
          return ele.id === item.id;
        });
        this.quotaList.splice(idx, 1);
      } else {
        let idx = this.dimensionList.findIndex((ele) => {
          return ele.id === item.id;
        });
        this.dimensionList.splice(idx, 1);
      }
    },
    handleDragNode(data) {
      if (data.isQuota) {
        this.selectNode = data;
      }
    },

    //拖拽指标
    dropRow() {
      if (this.rowList.length == 0) {
        if (!this.selectNode) {
          return;
        }
        if (this.selectNode.isQuota) {
          this.quotaList.push(this.selectNode);
          this.rowList.push(this.selectNode);
          this.selectNode = undefined;
        } else {
          this.dimensionList.push(this.selectNode);
          this.rowList.push(this.selectNode);
          this.selectNode = undefined;
        }
      } else {
        if (this.rowList[0].isQuota) {
          if (!this.selectNode) {
            return;
          }
          if (this.selectNode.isQuota) {
            this.quotaList.push(this.selectNode);
            this.rowList.push(this.selectNode);
            this.selectNode = undefined;
          } else {
            this.$message("请将维度拖到纵轴");
            this.selectNode = undefined;
          }
        } else {
          if (!this.selectNode) {
            return;
          }
          if (this.selectNode.isQuota) {
            this.$message("请将指标拖到纵轴");
            this.selectNode = undefined;
          } else {
            this.dimensionList.push(this.selectNode);
            this.rowList.push(this.selectNode);
            this.selectNode = undefined;
          }
        }
      }
    },
    dropCol() {
      if (!this.selectNode) {
        return;
      }
      if (this.colList.length === 0) {
        if (this.selectNode.isQuota) {
          this.quotaList.push(this.selectNode);
          this.colList.push(this.selectNode);
          this.selectNode = undefined;
        } else {
          this.dimensionList.push(this.selectNode);
          this.colList.push(this.selectNode);
          this.selectNode = undefined;
        }
      } else {
        if (this.colList[0].isQuota) {
          if (this.selectNode.isQuota) {
            this.quotaList.push(this.selectNode);
            this.colList.push(this.selectNode);
            this.selectNode = undefined;
          } else {
            this.$message("请将维度拖到横轴");
            this.selectNode = undefined;
          }
        } else {
          if (this.selectNode.isQuota) {
            this.$message("请将指标拖到横轴");
            this.selectNode = undefined;
          } else {
            this.dimensionList.push(this.selectNode);
            this.colList.push(this.selectNode);
            this.selectNode = undefined;
          }
        }
      }
    },
    childData(data) {
      if (data.tabComponent != undefined) {
        this.currentTabComponent = data.tabComponent;
      }
      if (data.themeId != undefined) {
        this.themeId = data.themeId;
      }
    },
  },
};
</script>
<style lang="less">
.ShowChart {
  // .chart {
  //   background: url(/chartsImg/table_group.png) center no-repeat;
  // }
  .chartType:hover {
    border: 1px solid #4b4c4d;
  }
  .el-icon-arrow-down {
    visibility: hidden;
  }
  .el-dropdown-link:hover .el-icon-arrow-down {
    visibility: visible;
  }
  .common {
    overflow: auto;
    text-align: left;

    .el-tree__empty-text {
      display: none;
    }
  }
  .chart {
    background-color: #fff;
  }

  .el-tree {
    display: inline-block;
  }

  .quotatree {
    overflow: auto;
  }

  .quoTree {
    text-align: left;
  }
  .el-tree__empty-text {
    display: none;
  }
}
.demonstration {
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei, Arial, sans-serif;
}
</style>
